<template>
  <div class="user-list-container">
    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        class="table"
      >
        <el-table-column prop="banner_id" label="ID" width="80" />
        <el-table-column prop="banner_title" label="轮播图标题" />
        <el-table-column prop="sort_order" label="排序" />
        <el-table-column label="是否启动" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.banner_status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button link @click="handleTableOption('edit', scope.row)"
              >编辑</el-button
            >
            <el-button link type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      title="轮播图"
      width="800"
      :before-close="handleCloseAddDialog"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="150px"
        class="demo-form"
      >
        <el-form-item label="标题" prop="banner_title">
          <el-input v-model="form.banner_title" />
        </el-form-item>
        <el-form-item label="图片" prop="image_url">
          <upload :img-file="form.image_url" :limit="1" @change="(val)=>{
            this.form.image_url = val
          }" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link_url">
          <el-input v-model="form.link_url" placeholder="请输入点击跳转链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input v-model="form.sort_order" type="number" />
        </el-form-item>
        <el-form-item label="是否启动" prop="banner_status">
          <el-switch
            v-model="form.banner_status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import upload from "@/components/upload.vue";

export default {
  name: "UserList",
  mixins: [tableMixin],
  components: { upload },
  data() {
    return {
      companyChildList: {},
      //查询参数
      queryParams: { insuranceEis_typeffectiveStatus: 0 },
      apimodel: "banner",
      apival: "getList",
      //创建修改弹窗
      dialogVisible: false,
      dialogType: "",
      form: {
        image_url: "",
        link_url: "",
        banner_title: "",
        sort_order: 0,
        banner_status: 1, // 默认启用
      },
      rules: {
        image_url: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
        banner_title: [
          { required: true, message: "请输入标题", trigger: "change" },
        ],
        sort_order: [
          { required: true, message: "请输入排序值", trigger: "change" },
        ],
      },
      companys: [],
      classlist: [],
    };
  },
  mounted() {
    api.classaa.getList({ size: 999 }).then((res) => {
      if (res.data.code == 200) {
        this.classlist = res.data.content.data;
      }
    });
  },
  methods: {
    // 状态切换
    handleStatusChange(row) {
      api.banner
        .updates({
          banner_id: row.banner_id,
          banner_status: row.banner_status,
        })
        .then((res) => {
          if (res?.status == 200) {
            this.$message.success("状态修改成功");
            this.getTableData();
          } else {
            // 恢复之前的状态
            row.banner_status = row.banner_status == 1 ? 0 : 1;
          }
        })
        .catch(() => {
          // 恢复之前的状态
          row.banner_status = row.banner_status == 1 ? 0 : 1;
        });
    },

    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
    },

    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        image_url: "",
        link_url: "",
        banner_title: "",
        sort_order: 0,
        banner_status: 1,
      };
      this.resetForm();
    },
    // 编辑
    handleTableOption(option, row) {
      if (option == "edit") {
        this.form = JSON.parse(JSON.stringify(row));
        this.openAddDialog(option);
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.banner
            .del({
              banner_id: row.banner_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 表单验证通过，提交逻辑
          if (this.dialogType != "edit") {
            api.banner.create(this.form).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          } else {
            api.banner.update(this.form).then((res) => {
              if (res?.status == 200) {
                this.$message.success("修改成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          }
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
    },
    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>